<?php
namespace Admin\Controller;

class PlanController extends Controller {

    public function index() {
        $m    = D2();
        $page = $m->where($this->indexExpr)->order($this->sortExpr)->page2();

        $this->assign('page', $page);
        $this->display();
    }

    public function  add() {
        $uid = I('get.uid', 0, 'intval');

        if (empty($uid)) {
            throw new \Exception('没有广告主编号，无法增加计划');
        }

        if (!$aderRecord = D('Ader')->getById($uid)) {
            throw new \Exception('没有找到广告主信息');
        }

        $record = [            
            'uid'       => $aderRecord['id'],
            'user_name' => $aderRecord['name'],
        ];

        $this->assign('record', $record)
             ->display();
    }

    public function detail() {
        $id = empty($_GET['id']) ? 0 : (int)$_GET['id'];

        if(empty($id)) {
            throw new \Exception('参数不完整，无法获取数据');
        }

        /**
         * 获取被限制投放的站长编号
         */
        if($limitSiter = D2('Siter')->getLimitByPlanId($id)) {
            $this->assign('limitSiter', $limitSiter);
        }

        $m = D2(CONTROLLER_NAME);

        if(!$record = $m->getByPlanId($id)) {
            throw new \Exception('没有找到计划信息');
        }

        $record['price']      = getPrice2($record['price']);
        $record['priceadv']   = getPrice2($record['priceadv']);
        $record['priceagent'] = getPrice2($record['priceagent']);

        $planDeviceModel = D2('PlanDevice');

        if (!$planDeviceRecords = $planDeviceModel->where(array('plan_id' => $id))->select()) {
            throw new \Exception('没有找到计划投放设备数据');
        }

        $record['pd_device'] = array();

        foreach ($planDeviceRecords as $k => $v) {
            $_device = $v['pd_device'];
            $record['pd_device'][] = $_device;
            $record["pd_url_{$_device}"]        = $v['pd_url'];
            $record["pd_price_{$_device}_1"]    = getPrice2($v['pd_price_1']);
            $record["pd_price_{$_device}_2"]    = getPrice2($v['pd_price_2']);
            $record["pd_price_{$_device}_3"]    = getPrice2($v['pd_price_3']);
            $record["pd_deduction_{$_device}"]  = $v['pd_deduction'];
            $record["pd_flow_scale_{$_device}"] = $v['pd_flow_scale'];
        }

        $this->assign('record', $record);
        $this->display();
    }

    public function modify() {
        $id = I('get.id', 0, 'intval');

        if (empty($id)) {
            throw new \Exception('参数不完整，无法获取数据');
        }

        $m = D('Plan');

        if (!$record = $m->getById($id)) {
            throw new \Exception('未找到广告计划数据');
        }

        if ($devicesOpts = $m->parseDeviceOpts($record['opts'])) {
            $record = array_merge($record, $devicesOpts);
            $devices = array_keys($record['devices']);
            $record['devices'] = $devices;  //将$record['devices']重置成已选择的设备编号列表
        }

        unset($record['opts']);

        $this->assign('record', $record)
             ->display();
    }

    public function doSave() {
        try {
            $r = D2()->save2($_POST)
                 ? ['s' => true,  'm' => '保存成功']
                 : ['s' => false, 'm' => '保存出错'];
        } catch (\Exception $e) {
            $r = ['s' => false, 'm' => $e->getMessage()];
        }

        showJson($r);
    }

    public function del() {
        $id = I('get.id', 0, 'intval');

        if (empty($id)) {
            showJson(['s' => false, 'm' => '参数不完整，无法删除数据']);
        }

        try {
            $r = D('Plan')->del($id) ? ['s' => true, 'm' => '删除成功'] : ['s' => false, 'm' => '删除出错'];
        } catch(\Exception $e) {
            $r = ['s' => false, 'm' => $e->getMessage()];
        }

        showJson($r);
    }

    /**
     * doPlay
     * 开启计划
     *
     * @return void
     */
    public function doPlay() {
        $id = I('get.id', 0, 'intval');

        if(empty($id)) {
            showJson(['s' => false, 'm' => '参数不完整']);
        }

        try {
            $r = D2()->play($id)
                 ? ['s' => true,  'm' => '计划开启成功']
                 : ['s' => false, 'm' => '计划开启失败'];
        } catch(\Exception $e) {
            $r = ['s' => false, 'm' => $e->getMessage()];
        }

        showJson($r);
    }

    /**
     * doStop
     * 停止计划
     *
     * @return void
     */
    public function doStop() {
        $id = I('get.id', 0);

        if(empty($id)) {
            showJson(array('s' => false, 'm' => '参数不完整'));
        }

        $m = D2();

        try {
            $r = D2()->stop($id)
                 ? array('s' => true, 'm' => '计划已停止')
                 : array('s' => false, 'm' => '计划停止失败');
        } catch(\Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * changeUrl
     * 批量修改网址
     *
     * @return void
     */
    public function changeUrl() {
        $id = I('get.id', 0, 'intval');

        if(empty($id)) {
            throw new \Exception('参数不完整，无法获取数据');
        }

        if(!$plan = D2()->getByPlanid($id)) {
            throw new \Exception('没有找到广告计划');
        }

        $mAd  = D2('Ad');
        $expr = array('plan_id' => $id);
        $record = $mAd->where($expr)->order('ad_id DESC')->select();

        if (!$planDeviceRecords = D2('PlanDevice')->where(array('plan_id' => $id))->order('pd_device ASC')->select()) {
            throw new \Exception("没有找到设备对应信息");
        }

        $this->assign(array(
            'record'       => $record,
            'plan'         => $plan,
            'plan_devices' => $planDeviceRecords
        ))->display();
    }

    /**
     * doChangeUrl
     * 批量替换广告网址
     *
     * @return void
     */
    public function doChangeUrl() {
        $m = D2();
        $d = I('post.');

        try {
            $m->changeUrl($d);
            $r = array('s' => true, 'm' => '修改网址成功');
        } catch(\Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * move
     * 移动广告计划至其它广告主名下
     *
     * @return void
     */
    public function move() {
        $order = 'status ASC, uid DESC';
        $plan = D2()->order('planid DESC')->order($order)->select();
        $ader = D2('Ader')->where(array('type' => AderModel::TYPE,  'status' => 2))->order('uid DESC')->select();

        $this->assign('plan', $plan)->assign('ader', $ader);
        $this->display();
    }

    /**
     * doMove
     * 执行转移计划操作
     *
     * @return void
     */
    public function doMove() {
        $d = $_POST;

        if(empty($d['plan_id']) || !is_array($d['plan_id'])) {
            showJson(array('s' => false, 'm' => '请选择待转移的广告计划'));
        }

        if(empty($d['uid'])) {
            showJson(array('s' => false, 'm' => '请选择接收转移计划的广告主'));
        }

        $planIds = $d['plan_id'];
        $uid     = $d['uid'];

        try {
            $msg = D2()->move($planIds, $uid)
                   ? array('s' => true, 'm' => '计划转移成功')
                   : array('s' => false, 'm' => '计划转移出错');
        } catch(\Exception $e) {
            $msg = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($msg);
    }

    /**
     * tmpUpPlanDevice
     * 升级plan表部分字段值到plan_device表中
     *
     * @return void
     */
    public function tmpUpPlanDevice() {
        $offset = 0;
        $limit  = 500;
        $m = D2('Plan');
        $planDeviceModel = D2('PlanDevice');

        $_limit = "{$offset},{$limit}";

        while ($records = $m->order('planid DESC')->limit($_limit)->select()) {
            foreach ($records as $_plan) {
                $planDeviceModel->startTrans();

                if (!empty($_plan['url'])) {
                    $_dao = array(
                        'plan_id'      => $_plan['planid'],
                        'pd_url'       => $_plan['url'],
                        'pd_device'    => 1,
                        'pd_price_1'   => getPrice2($_plan['priceadv']),   //广告主单价
                        'pd_price_2'   => getPrice2($_plan['priceagent']), //代理商单价
                        'pd_price_3'   => getPrice2($_plan['price']),      //站长单价
                        'pd_deduction' => $_plan['deduction'],
                    );

                    if (!$planDeviceModel->save2($_dao)) {
                        $planDeviceModel->rollback();
                        exit($_plan['plan_id'] . ' up error');
                    }
                }

                /**
                 * url2对应的是移动端网址
                 */
                if (!empty($_plan['url2'])) {
                    $_dao = array(
                        'plan_id'      => $_plan['planid'],
                        'pd_url'       => $_plan['url2'],
                        'pd_device'    => 2,                     //Android
                        'pd_price_1'   => getPrice2($_plan['priceadv']),
                        'pd_price_2'   => getPrice2($_plan['priceagent']),
                        'pd_price_3'   => getPrice2($_plan['price']),
                        'pd_deduction' => $_plan['deduction_2'],
                    );

                    if (!$planDeviceModel->save2($_dao)) {
                        $planDeviceModel->rollback();
                        exit($_plan['plan_id'] . ' up error');
                    }

                    $_dao['pd_device'] = 3; //IOS

                    if (!$planDeviceModel->save2($_dao)) {
                        $planDeviceModel->rollback();
                        exit($_plan['plan_id'] . ' up error');
                    }

                    $_dao['pd_device'] = 4; //Windows Phone

                    if (!$planDeviceModel->save2($_dao)) {
                        $planDeviceModel->rollback();
                        exit($_plan['plan_id'] . ' up error');
                    }
                }

                $planDeviceModel->commit();
            }

            $offset += $limit;
            $_limit = "{$offset},{$limit}";
        }

        echo 'Finish';
    }

}
